package com.javaweb.blogcite.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javaweb.blogcite.DTO.LoginRequest;
import com.javaweb.blogcite.DTO.LoginResponse;
import com.javaweb.blogcite.mapper.LoginMapper;
import com.javaweb.blogcite.pojo.Admin;
import com.javaweb.blogcite.service.LoginService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Admin> implements LoginService{

    @Resource
    private LoginMapper loginMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public LoginResponse login(LoginRequest loginRequest, HttpServletResponse response, Integer remember) {
        Admin admin = loginMapper.selectByLoginId(loginRequest.getLoginId());
        if (admin.getLoginPwd().equals(loginRequest.getLoginPwd())){
            // 生成Token并添加到响应头
            long expirationTime = System.currentTimeMillis() + remember * 24 * 60 * 60 * 1000;
            String token = Jwts.builder()
                    .setSubject(admin.getId())
                    .setExpiration(new Date(expirationTime))
                    .signWith(SignatureAlgorithm.HS256, secret)
                    .compact();
            response.addHeader("Authentication", token);

            return new LoginResponse(admin.getLoginId(),admin.getName(),admin.getId());
        }else {
            return null;
        }
    }

    @Override
    public LoginResponse whoami(String userId) {
        Admin admin = loginMapper.selectById(userId);
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setLoginId(admin.getLoginId());
        loginResponse.setName(admin.getName());
        loginResponse.setId(admin.getId());
        return loginResponse;
    }
}
